package org.java;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFuture {
	public static void main(String[] args) {
		

		/*
		 * Executor 有个子接口ExecutorService，ExecutorService才有shutdown()
		 * Executors.newFixedThreadPool(3);返回ExecutorService
		 */
		Executor executor = Executors.newFixedThreadPool(10);
		/* CompletionService 将生产新的异步任务与使用已完成任务的结果分离开来的服务。 */
		CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
		// 提交10个任务
		for (int i = 1; i <= 100; i++) {
			final int temp = i;
			System.out.println(temp);
			completionService.submit(new Callable<String>() {

				@Override
				public String call() throws Exception {
					Thread.sleep(10000/temp);
					// TODO Auto-generated method stub
					return Thread.currentThread().getName() + "得到的结果是" + temp + ",sleep:" + 10000/temp;
				}
			});
		}
		// 10个任务，10个返回结果，
		for (int i = 0; i < 100; i++) {
			try {
				/*
				 * 这些任务计算的时间不同， 所以结果队列顺序不一定
				 */
				// take(),返回并移除已完成的Future
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}